<template>
  <div class="ele-body">
    <a-card :title="supplyMaterialListApp.title" :bordered="false" class="my-grid66" v-if="isRouterAlive">
      <div class="edit-order" v-if="orderId">
        <div class="order" style="display: flex">
          <div>订单编号:</div>
          <div>{{ orderId }}</div>
        </div>
        <a @click="clearEdit">放弃订单修改</a>
      </div>

      <vxe-table border :data="cart" :row-class-name="tableRowClassName" ref="cartListGrid" v-bind="gridOptions">
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column field="name" title="供应材料名称">
        </vxe-column>
        <vxe-column field="supplierName" title="供应商名称">
        </vxe-column>
        <vxe-column field="quantity" title="数量" formatter="dataFormat"></vxe-column>
        <vxe-column field="price" title="单价" formatter="dataFormat"></vxe-column>
        <vxe-column field="totalPrice" title="合计" formatter="dataFormat"></vxe-column>
        <vxe-column field="operate" title="操作">
          <template #default="{row}">
            <a-space>
              <a @click="editEvent(row)">修改</a>
              <a-divider type="vertical"/>
              <a-popconfirm
                title="确定要删除此材料吗？"
                @confirm="deleteEvent(row)">
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </vxe-column>

      </vxe-table>


      <a-row :md="12" :sm="24" :xs="24">
        <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
          <!--class="ele-pull-right"-->
          <div>
            <teleport to="#supplyMaterialOrderListModalFooter">
              <div>
                <a-space size="middle">
                  <a-button @click="onBack()">取消
                  </a-button>
                  <a-button
                    type="primary"
                    @click="onSubmit(cart)"
                    :loading="loading">提交订单
                  </a-button>
                </a-space>
              </div>
            </teleport>
          </div>
        </a-form-item>
      </a-row>

      <!--加入到采购单弹窗-->
      <vxe-modal v-model="supplyMaterialListApp.orderModalShowing" title="修改材料数量"
                 id="supplyMaterialOrderModal"
                 width="600"
                 min-width="460"
                 min-height="320"
                 :destroy-on-close="true"
                 :lock-view="false" :mask="false"
                 footer
                 show-footer show-zoom resize remember storage transfer dblclickZoom>
        <template #default>
          <div id="supplyMaterialOrderModalContent">
          </div>
        </template>
        <template #footer>
          <div id="supplyMaterialOrderModalFooter">
          </div>
          <teleport to="#supplyMaterialOrderModalContent">
            <SupplyMaterialOrder ref="supplyMaterial-order" @editClose="getEditClose"/>
          </teleport>
        </template>
      </vxe-modal>
    </a-card>

  </div>
</template>

<script>
import {defineComponent, reactive, ref, toRefs, provide, computed, nextTick} from 'vue'//, Ref
import {VXETable} from 'vxe-table'//, VxeGridInstance, VxeGridProps
// import XEAjax from 'xe-ajax'
// import {SupplyMaterialService} from "@/views/restaurant/material/supplyMaterial/supplyMaterialService";
// import {OrderMaterialRelationService} from "@/views/restaurant/material/orderMaterialRelation/orderMaterialRelationService";
import {MaterialOrderService} from "@/views/restaurant/material/materialOrder/materialOrderService";
import SupplyMaterialOrder
  from "@/views/restaurant/material/supplyMaterial/supplyMaterial-order";
import {useRouter} from "vue-router";

export default defineComponent({
  components: {
    SupplyMaterialOrder,
  },
  emits: ['orderId','orderListModalShowing'],
  setup(props, {emit}) {
    let cart = reactive(JSON.parse(localStorage.getItem('cart')) || [])
    console.log(cart)
    const router = useRouter();
    let orderId = ref(router.currentRoute.value.query.orderId ? router.currentRoute.value.query.orderId : null);
    const queryParams = {}
    let editClose = ref(false)
    VXETable.formats.add('dataFormat', ({ cellValue }) => {
      if(cellValue!==null){
        return cellValue.toFixed(2)
      }
    })
    queryParams.currentPage = 1
    queryParams.pageSize = 10
    // console.log(OrderMaterialRelationService.findOrderMaterialRelations(queryParams))
    console.log(cart)
    const cartListGrid = ref({})// as VxeGridInstance
    // 搜索表单是否展开
    let searchExpand = ref(false)
    let proxyInfo = reactive({})
    const where = ref({})
    const eid = ref({})
    let isRouterAlive = ref(true)
    // let cartTotalPrice = cart.reduce((pre, cur) => {
    //   return pre + cur.totalPrice;
    // }, 0)
    console.log(cartTotalPrice)


    let cartTotalPrice = computed({
      get() {
        return cart.reduce((pre, cur) => {
          return pre + cur.totalPrice;
        }, 0).toFixed(2)
      }
      ,
      set(newVal) {
        console.log(newVal)
        cartTotalPrice = newVal.toFixed(2)
        supplyMaterialListApp.title = `总价格 ${newVal.toFixed(2)}`
      }
    })
    const supplyMaterialListApp = reactive({
      editModalShowing: false,
      viewModalShowing: false,
      orderModalShowing: false,
      orderListModalShowing: false,
      editModalForEdit: false,
      addModalForEdit: false,
      orderModalForEdit: false,
      title: `总价格 0`
    })
    // supplyMaterialListApp.title = ref('总价格 '+(cartTotalPrice.value?cartTotalPrice.value:'0'))

    supplyMaterialListApp.title = computed(() => {
        console.log(cartTotalPrice)
        return '总价格 ' + (cartTotalPrice.value ? cartTotalPrice.value : '0');
      }
    )
    provide('supplyMaterialListApp', supplyMaterialListApp)
    provide('cartListGrid', cartListGrid)
    let orderListModalShowing = ref(true);
    const getEditClose = () => {
      console.log("触发emit")
      let change = JSON.parse(localStorage.getItem('cart')) || []
      console.log(change)
      Object.assign(cart,change)//改变reactive响应式对象，不能直接赋值！！！（xdl）
      // cart = change
      nextTick(()=>{
        reload()
      })
      // console.log(editClose)
    }
    /*TODO:数据表列*/
    const columns = [
      /*多选checkbox 单选seq*/
      // {type: 'seq', title: '#', width: 40},
      // {type: 'checkbox', field: 'eid', title: 'ID', width: 100, sortable: true},
      {
        dataIndex: 'materialId',
        title: '材料id',
        key: 'materialId',
      },
      {
        dataIndex: 'name',
        title: '供应原材料名称',
        key: 'materialId',
      },
      {
        dataIndex: 'price',
        title: '价格',
        formatter({cellValue}){
          if(cellValue!=null){
            return cellValue.toFixed(2)
          }
        }
      },
      {
        dataIndex: 'quantity',
        title: '数量',
        formatter({cellValue}){
          if(cellValue!=null){
            return cellValue.toFixed(2)
          }
        }
      },

      {
        dataIndex: 'operate',
        key: 'operate',
        title: '操作',
        width: 250,
        customRender: () => {
          return
        },
      }


    ]


    const tableRowClassName = ({row, rowIndex}) => {
      //把每一行的索引放进row
      row.index = rowIndex;
    }


    /*TODO:新建事件*/
    const addEvent = () => {
      supplyMaterialListApp.editModalShowing = true
      supplyMaterialListApp.currentId = null;
      supplyMaterialListApp.addModalForEdit = true;
      // gridOptions.showEditTitle = "新建";
    }
    /*TODO:查看采购单*/
    const viewOrderList = () => {
      // router.push(`/restaurant/material/supplyMaterial/supplyMaterial-edit/${eid}`);
      supplyMaterialListApp.orderListModalShowing = true;
      supplyMaterialListApp.orderModalForEdit = true;
      // gridOptions.OrderDetailsTitle = "查看采购单";
    }
    /*TODO:编辑事件*/
    const editEvent = (row) => {
      supplyMaterialListApp.orderModalShowing = true;
      supplyMaterialListApp.currentId = row.eid;
      supplyMaterialListApp.orderModalForEdit = true;
      supplyMaterialListApp.cart = row;

    }
    /*TODO:编辑事件*/
    const onBack = () => {
      emit('orderListModalShowing',false);
    }

    /*TODO:添加到采购单*/
    const addToOrder = (row) => {
      supplyMaterialListApp.orderModalShowing = true;
      supplyMaterialListApp.currentId = row.eid;
      supplyMaterialListApp.orderModalForEdit = true;
      // gridOptions.OrderDetailsTitle = "添加到采购单";
    }
    /*TODO:查看采购单*/
    const viewOrder = () => {
      // router.push(`/restaurant/material/supplyMaterial/supplyMaterial-edit/${eid}`);
      supplyMaterialListApp.orderListModalShowing = true;
      // gridOptions.OrderDetailsTitle = "查看采购单";
    }
    /*TODO:提交订单*/

    const onSubmit = (data) => {
      let datas = toRefs(data)
      console.log(datas);
      if (!data.length) {
        VXETable.modal.message({content: "请至少加入一条数据", status: 'info'})
        return
      }
      console.log(cart)


      let orderData = {
        price: parseFloat(cartTotalPrice.value)
      }
      orderData.supplyMaterialList = data
      console.log(orderData)
      if (orderId.value) {//修改
        MaterialOrderService.findMaterialOrder(orderId.value).then(res => {
          console.log(res)
          let editOrder = res.data;
          if (editOrder.status != '待审核' && editOrder.status != '打回'&& editOrder.status != '待提交') {
            VXETable.modal.message({content: "不允许修改该订单", status: 'error'})
            return
          }
          editOrder.price = parseFloat(cartTotalPrice.value);
          editOrder.supplyMaterialList = data;
          MaterialOrderService.updateMaterialOrder(editOrder).then((res) => {
            console.log(res);
            clearEdit();
            VXETable.modal.message({content: '提交成功', status: 'success'});
            localStorage.setItem('cart', JSON.stringify([]));
            // cart.value = []
            cart.splice(0, cart.length);
            // cartTotalPrice.value = 0;
            console.log(cartTotalPrice)
            reload();
          }).catch(e => {
            VXETable.modal.message({content: e.message, status: 'error'})
          })
        })

      } else {
        //创建订单
        MaterialOrderService.saveMaterialOrder(orderData).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '提交成功', status: 'success'});
          cart.splice(0, cart.length);
          localStorage.setItem('cart', JSON.stringify([]));
          // cart.value = []
          cartTotalPrice = 0;
          console.log(cart)
          console.log(cartTotalPrice)
          reload();
        })
      }


    }

    /*TODO:编辑关闭事件*/
    const editEventClose = () => {
      // console.log(gridOptions.formData);
      VXETable.modal.message({content: '提交成功', status: 'success'})
    }

    /*TODO:查看事件*/
    const viewEvent = (row) => {
      supplyMaterialListApp.currentId = row.eid;
      supplyMaterialListApp.viewModalShowing = true
      // gridOptions.showDetailsTitle = '查看';
    }

    /*TODO:删除事件*/
    const deleteEvent = (row) => {
      let index = row.index;
      cart.splice(index, 1);
      console.log(index)
      localStorage.setItem('cart', JSON.stringify(cart));
      console.log(cart)
      VXETable.modal.message({content: '移除成功', status: 'success'})
      reload();
    }
    /*TODO:放弃订单修改*/
    const clearEdit = () => {
      router.push({query: {}})
      // router.currentRoute.value.query.orderId = null;
      orderId.value = null;
      // isRouterAlive = false;
      console.log(orderId)
      emit('orderId', null);
      VXETable.modal.message({content: '已回到新建订单模式', status: 'success'})
    }

    /*TODO:批量删除*/
    const batchDeleteEvent = () => {
      VXETable.modal.message({content: '点了批量删除', status: 'success'})
    }

    /*TODO:局部刷新*/
    const reload = () => {
      console.log("刷新", cart)
      const $grid = cartListGrid.value
      $grid.loadData(cart);
    }
    // provide('reload',reload)
    provide('grid', cartListGrid.value)

    /*TODO:重置搜索*/
    const reset = () => {
      where.value = {}
      const $grid = cartListGrid.value
      $grid.commitProxy('query')//TODO:执行代理方法
    }

    //TODO:这里需要返回才能调用
    return {
      eid,
      cartListGrid,
      // editModal,
      columns,
      searchExpand,
      cart,
      isRouterAlive,
      editClose,
      orderId,
      orderListModalShowing,
      viewOrder,
      onSubmit,
      addEvent,
      editEvent,
      viewEvent,
      onBack,
      editEventClose,
      deleteEvent,
      batchDeleteEvent,
      addToOrder,
      viewOrderList,
      getEditClose,
      clearEdit,
      where,
      reload,
      reset,
      supplyMaterialListApp,
      tableRowClassName,
      ...toRefs(proxyInfo)
    }
  }
})
</script>

<style scoped>
.edit-order {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.my-grid66 .alert-message {
  height: 40px;
  display: flex;
  align-items: center;
  margin: 10px 0;
  border-radius: 4px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.my-grid66 .alert-message-icon {
  width: 30px;
  text-align: center;
  color: #409eff;
  margin-right: 8px;
}

.my-grid66 .alert-message-content {
  flex-grow: 1;
  padding-right: 20px;
}

.my-grid66 .page-left {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
}

.my-grid66 .select-count {
  display: inline-block;
  vertical-align: middle;
}

.my-grid66 .my-input {
  width: 100%;
}

.my-grid66 .first-col {
  position: relative;
  height: 20px;
}

.my-grid66 .first-col:before {
  content: "";
  position: absolute;
  left: -15px;
  top: 10px;
  width: 110px;
  height: 1px;
  transform: rotate(28deg);
  background-color: #e8eaec;
}

.my-grid66 .first-col .first-col-top {
  position: absolute;
  right: 4px;
  top: -10px;
}

.my-grid66 .first-col .first-col-bottom {
  position: absolute;
  left: 4px;
  bottom: -10px;
}
</style>
